﻿using System;
using System.Collections.Generic;
using LujHosting.Internal;
using Microsoft.Extensions.Hosting;

namespace LujHosting;

public static class HostConfigureExt {

  public record ServiceItem(Type Type, object Instance);

  public static IHostBuilder ConfigureServiceAuto<S>(this IHostBuilder hostBuilder) where S : class {
    return ConfigureServiceAuto<S>(hostBuilder, Array.Empty<ServiceItem>());
  }

  public static IHostBuilder ConfigureServiceAuto<S>(this IHostBuilder hostBuilder, List<ServiceItem> init) where S : class {
    return ConfigureServiceAuto<S>(hostBuilder, (IList<ServiceItem>)init);
  }

  public static IHostBuilder ConfigureServiceAuto<S>(this IHostBuilder hostBuilder, IList<ServiceItem> init) where S : class {
    Type rootService = typeof(S);

    var depCollect = RootDependencyCollector.New(rootService, init);
    ServiceAutoConfig auto = new(depCollect, init);

    Type[] groupEx = { typeof(IHostedService) };
    return hostBuilder.ConfigureServices(s => auto.Configure(groupEx, s));
  }
}
